package com.hxkj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.AuthUserServiceClient;
import com.hxkj.domain.enums.AuthRoleExceptionEnum;
import com.hxkj.domain.enums.UserExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.service.AuthUserService;
import com.hxkj.token.TokenGenerator;
import com.hxkj.token.utils.TokenUtils;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultMessageStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @ClassName AuthUserServiceImpl
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/5/23 19:01
 * @Version 1.0
 */
@Service
@Slf4j
public class AuthUserServiceImpl implements AuthUserService {

    @Autowired
    private AuthUserServiceClient authUserServiceClient;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private TokenGenerator generator;

    @Override
    public ResultPageStruct<AllocationAuthUser> getAuthUserBySlave(AuthUser authUser, PageTo pageParam) throws Exception {
        ResultPageStruct<AllocationAuthUser> resultPageStruct = new ResultPageStruct<>();
        if (pageParam.getPageNum() == null) {
            pageParam.setPageNum(1);
        }
        if (pageParam.getPageSize() == null) {
            pageParam.setPageSize(20);
        }
        try {
            ParameterDataStruct<AuthUser> parameterDataStruct = new ParameterDataStruct<>();
            parameterDataStruct.setData(authUser);
            parameterDataStruct.setPageTo(pageParam);

            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            authUser.setUserId(auser.getUserId());
            parameterDataStruct.setData(authUser);

            resultPageStruct = authUserServiceClient.getUserBySlave(parameterDataStruct);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取用户列表失败:{}", e.getMessage());
        }
        return resultPageStruct;
    }

    @Override
    public JSONObject getAuthUser(AuthUser authUser) throws Exception {
        ResultDataStruct<JSONObject> resultDataStruct;
        //Mr.zheng: 抛出异常，用户不存在
        if (authUser.getUserId() == null) {
            throw new CustomException(UserExceptionEnum.USER_NOT_EXIST);
        }
        try {
            resultDataStruct = authUserServiceClient.getAuthUser(authUser);
            if (resultDataStruct.getCode() == 200) {
                JSONObject allocationAuthUser = resultDataStruct.getData();
                return allocationAuthUser;
            } else {
                throw new CustomException(UserExceptionEnum.getEnumByCode(resultDataStruct.getCode()));
            }
        } catch (CustomException e) {
            log.error("获取用户信息失败:{}", e.getMessage());
            e.printStackTrace();
            throw e;
        } catch (Exception e) {

            throw e;
        }
    }

    @Override
    public ResultMessageStruct saveAuthUser(AuthUser authUser) throws Exception {
        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
        if (null == authUser.getUserAccount() || authUser.getUserAccount().equals("")) {
            throw new CustomException(UserExceptionEnum.USER_ACCOUNT_NOT_NULL);
        }
        if (null == authUser.getUserName() || authUser.getUserName().equals("")) {
            throw new CustomException(UserExceptionEnum.USER_NAME_NOT_NULL);
        }
        if (null == authUser.getPassword() || authUser.getPassword().equals("")) {
            throw new CustomException(UserExceptionEnum.USER_PASSWORD_NOT_NULL);
        }
        try {
            resultMessageStruct = authUserServiceClient.saveUser(authUser);
            if (resultMessageStruct.getCode() == 200) {
                return resultMessageStruct;
            } else {
                throw new CustomException(UserExceptionEnum.getEnumByCode(resultMessageStruct.getCode()));
            }
        } catch (Exception e) {
            log.error("添加用户信息失败:{}", e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void userLock(String uid) throws Exception {
    }

    @Override
    public ResultMessageStruct updateAuthUser(AuthUser authUser) throws Exception {
        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
        //Mr.zheng:判断用户ID是否存在
        if (authUser.getUserId() == null) {
            resultMessageStruct.setCode(UserExceptionEnum.USER_NOT_UID.getCode());
            resultMessageStruct.setMessage(UserExceptionEnum.USER_NOT_UID.getMsg());
            return resultMessageStruct;
        }
        try {
            resultMessageStruct = authUserServiceClient.updateAuthUser(authUser);
            if (resultMessageStruct.getCode() == 200) {
                return resultMessageStruct;
            } else {
                throw new CustomException(UserExceptionEnum.getEnumByCode(resultMessageStruct.getCode()));
            }
        } catch (Exception e) {
            log.error("修改用户信息失败:{}", e.getMessage());
            throw e;
        }
    }

    @Override
    public ResultMessageStruct deleteAuthUser(AuthUser authUser) throws Exception {
        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
        if (authUser.getUids() == null) {
            resultMessageStruct.setCode(UserExceptionEnum.PLEASE_SELECT_USER.getCode());
            resultMessageStruct.setMessage(UserExceptionEnum.PLEASE_SELECT_USER.getMsg());
            return resultMessageStruct;
        }
        try {
            resultMessageStruct = authUserServiceClient.deleteAuthUser(authUser);
            if (resultMessageStruct.getCode() == 200) {
                return resultMessageStruct;
            } else {
                throw new CustomException(UserExceptionEnum.getEnumByCode(resultMessageStruct.getCode()));
            }
        } catch (Exception e) {
            log.error("删除用户信息失败:{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 把用户关联到角色
     *
     * @param authRole
     * @return
     * @throws Exception
     */
    @Override
    public ResultMessageStruct addUsertToRole(AuthRole authRole) throws Exception {
        if (authRole == null) {
            throw new CustomException(AuthRoleExceptionEnum.PARAMETER_IS_NULL);
        }
        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
        try {
            resultMessageStruct = authUserServiceClient.addUsertToRole(authRole);
            if (resultMessageStruct.getCode() == 200) {
                return resultMessageStruct;
            } else {
                throw new CustomException(AuthRoleExceptionEnum.getEnumByCode(resultMessageStruct.getCode()));
            }
        } catch (Exception e) {
            log.error("更改用户角色信息失败:{}", e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 查询该角色关联的所有用户
     *
     * @param authRole
     * @return
     * @throws Exception
     */
    @Override
    public AllocationUser getRoleAssignUser(AuthRole authRole) throws Exception {
        if (authRole == null) {
            throw new CustomException(AuthRoleExceptionEnum.PARAMETER_IS_NULL);
        }
        ResultDataStruct<AllocationUser> resultDataStruct = new ResultDataStruct<>();
        try {
            resultDataStruct = authUserServiceClient.getRoleAssignUser(authRole);
            if (resultDataStruct.getCode() == 200) {
                return resultDataStruct.getData();
            } else {
                throw new CustomException(AuthRoleExceptionEnum.getEnumByCode(resultDataStruct.getCode()));
            }
        } catch (Exception e) {
            log.error("获取用户角色信息失败:{}", e.getMessage());
            throw e;
        }
    }

    @Override
    public void updateAuthUserPassword(AuthUser authUser) throws Exception {
        ResultMessageStruct resultMessageStruct = new ResultMessageStruct();
        //Mr.zheng:判断用户ID是否存在
        if (authUser.getUserId() == null) {
            throw new CustomException(UserExceptionEnum.USER_NOT_UID);
        }
        try {
            resultMessageStruct = authUserServiceClient.updateAuthUserPassword(authUser);
            if (resultMessageStruct.getCode() == 200) {
                //Mr.zheng:修改密码成功退出登录状态重新登录
                userService.loginOut(String.valueOf(authUser.getUserId()));
            } else {
                throw new CustomException(UserExceptionEnum.getEnumByCode(resultMessageStruct.getCode()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改用户信息失败:{}", e.getMessage());
            throw e;
        }
    }

    //Mr.zheng:重置密码后将所有在线用户踢下线
    private void loginOutAll(String userId) throws Exception {
        generator.generatorOutAll(userId);
        tokenUtils.invalidUserInfo(userId);
    }
}
